//路由鉴权
import router from "./router";
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
//获取用户仓库
import useUserStore from "./store/modules/user";
import pinia from "./store";
import setting from "./setting";
let userStore = useUserStore(pinia)
nprogress.configure({showSpinner: false})
//全局守卫：项目当中任意路由切换都会触发的钩子
//全局前置守卫
router.beforeEach(async (to, _, next) => {
    // document.title =  setting.title + ' - '+ to.meta.title
    document.title = `${setting.title} - ${to.meta.title}`
    //to:即将要进入的那个路由
    //from:当前在那个路由
    //next:放行函数
    //路由鉴权
    nprogress.start()
    let token = userStore.token
    //获取用户名字
    let username = userStore.username
    if (token) {
        if (to.path == '/login') {
            next('/')
        } else {
            if (username) {
                next()
            } else {
                try {
                    await userStore.userInfo()
                    //如果刷新的页面是异步路由，有可能获取到用户信息时，异步路由还没有添加到路由表中，出现空白的效果
                    //{...to}保证加载完后再放行
                    next({...to})
                } catch (error) {
                    //token过期或者无效
                    await userStore.userLogout()
                    next({path: '/login', query: {redirect: to.path}})
                }
            }
            
        }
    }else {
        if (to.path == '/login' || to.path == '/screen') {
            next()
        } else {
            next({path: '/login', query: {redirect: to.path}})
        }
    }

})
//全局后置守卫
router.afterEach((_to, _from) => {
    //to:即将要进入的那个路由
    //from:当前在那个路由
    nprogress.done()
})

